package com.appliance.cycling2011.download;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.os.Environment;

public class DownloadHtmlModifyThread extends DownloadSpecificThread {

	String htmlVmNewsFilePath;
	boolean singleNews = false;

	public DownloadHtmlModifyThread(String url, String directory, String filename, String extension, boolean single) {
		super(url, directory, filename, extension);
		htmlVmNewsFilePath = Environment.getExternalStorageDirectory() + directory + filename + "." + extension;
		singleNews = single;
	}

	@Override
	public void run() {
		if (DownloadFromUrl(url, PATH_DIR, filename, extension, 0)) {
			setup();
		}
	}

	public void setup() {
		StringBuilder sBuilder = readFile();

		File file = new File(htmlVmNewsFilePath);
		// Log.e("filepath", htmlVmNewsFilePath);
		BufferedWriter writer;
		try {
			writer = new BufferedWriter(new FileWriter(file));
			writer.write(sBuilder.toString());
			writer.flush();
			writer.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	protected StringBuilder readFile() {
		InputStream instream = null;
		StringBuilder total = new StringBuilder();

		try {
			// open the file for reading
			instream = new FileInputStream(htmlVmNewsFilePath);

			// if file is available for reading
			if (instream != null) {

			}
		} catch (java.io.FileNotFoundException e) {
			// Log.i("## readFile", filename);
		}

		InputStreamReader inputreader = new InputStreamReader(instream);
		BufferedReader buffR = new BufferedReader(inputreader);

		String line;
		try {
			while ((line = buffR.readLine()) != null) {
				total.append(modify(line));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Log.i("## loading", "success");
		return total;
	}

	private String modify(String line) {
		if (line.contains("images/top.png") || line.contains("../images/bund") || line.contains("DK-2605"))
			return "";
		if (line.contains("NEWS</div>") || line.contains("COURSES</div>") || line.contains("PROGRAMME</div>")
				|| line.contains("GUIDE</div>") || line.contains("MORE</div>")) {
			return "";
		}
		if (line.contains("../images/nyheder"))
			return line.replace("../images", "http://www.copenhagen2011.dk/images");
		if (!singleNews && line.contains("index.php?p=nyheder")) {
			String nyhedNr = line.substring(line.indexOf("nyhed=") + 6, line.indexOf("\">"));
			String url = "http://www.copenhagen2011.dk/m/index.php?p=nyheder/profil.php&nyhed=" + nyhedNr;

			new DownloadHtmlModifyThread(url, directory, nyhedNr, extension, true).start();

			return "<a href=\"" + PATH_DIR + nyhedNr + ".html" + "\"> ";
		}

		return line;
	}

}
